# -*- coding: utf-8 -*-
import pendulum
from datetime import timedelta
from utils.operators.cluster_for_spark_sql_operator import SparkSqlOperator
from spmi_dm_rebate.dm.dm_volume_policy_rebate import spmi_dm__dm_volume_policy_rebate
from airflow.exceptions import AirflowSkipException
from airflow.models import Variable

# pro
# tidb_host = Variable.get('bigdata_tidb_host')
# tidb_port = Variable.get('bigdata_tidb_port')
# tidb_url = Variable.get('bigdata_tidb_url')
# tidb_user = Variable.get('bigdata_tidb_user')
# tidb_password = Variable.get('bigdata_tidb_password')

# uat
# tidb_host = "uat-jms-tidb.yl.com"
# tidb_port = 4001
# tidb_url = "jdbc:mysql://uat-jms-tidb.yl.com:4001/spmi_dm?useUnicode=true"
# tidb_user = "yl_spmibill_report_rw"
# tidb_password = "ZzA^G@4oJFCIjGbk"

#Hive表名
hive_table = "dm_volume_policy_rebate"
#任务名
task_id = f"tidb_dm__{hive_table}"

cst = pendulum.timezone('Asia/Shanghai')
class VolumeRebateSqlSensor(SparkSqlOperator):

    def pre_execute(self, context):
        day = cst.convert(context['ti'].execution_date) + timedelta(days=1)

        schedule_date = ['02']

        if day.strftime('%d') not in schedule_date:
            print(f'{day.strftime("%d")} not in {schedule_date}, should skip')
            super().pre_execute(context)
            raise AirflowSkipException()
        else:
            print(f'{day.strftime("%d")} in {schedule_date}, run now')
            super().pre_execute(context)


spmi_dm__tidb_dm_volume_policy_rebate = VolumeRebateSqlSensor(
    task_id=f'{task_id}',
    task_concurrency=1,
    pool_slots=2,
    master='yarn',
    name=f'{task_id}_{{ execution_date | date_add(1) | cst_ds }}',
    sql=f'spmi_dm_rebate/tidb/tidb_dm_volume_policy_rebate/execute.sql',
    retries=0,
    pool='spmi_piece',
    email=['yushuo@jtexpress.com', 'yl_bigdata@yl-scm.com'],
    execution_timeout=timedelta(hours=1),
    yarn_queue='pro',
    driver_memory='4G',
    driver_cores=2,
    executor_cores=4,
    executor_memory='4G',
    num_executors=1,  # spark.dynamicAllocation.enabled 为 True 时，num_executors 表示最少 Executor 数
    conf={'spark.dynamicAllocation.enabled': 'true',  # 动态资源开启
          'spark.shuffle.service.enabled': 'true',  # 动态资源 Shuffle 服务开启
          'spark.dynamicAllocation.maxExecutors': 2,  # 动态资源最大扩容 Executor 数
          'spark.dynamicAllocation.cachedExecutorIdleTimeout': 120,  # 动态资源自动释放闲置 Executor 的超时时间(s)
          'spark.sql.sources.partitionOverwriteMode': 'dynamic',  # 允许删改已存在的分区
          'spark.executor.memoryOverhead': '2G',  # 堆外内存
          'spark.sql.shuffle.partitions': 200,
          },
    hiveconf={'hive.exec.dynamic.partition': 'true',  # 动态分区
              'hive.exec.dynamic.partition.mode': 'nonstrict',
              'hive.exec.max.dynamic.partitions': 100,
              'hive.exec.max.dynamic.partitions.pernode': 100,
              },

)

spmi_dm__tidb_dm_volume_policy_rebate << spmi_dm__dm_volume_policy_rebate